<template>
<div>
  <div class="search">
    <input v-model="keyword" type="text" placeholder="请输入城市" class="searchinput" maxlength="20">
  </div>
  <div>
    <div class="search-content" ref="search" v-if="showcity">
      <ul>
        <li class="search-item border-bottom" v-for="item of list" @click="handleClickName(item.name)" >{{item.name}}</li>
           <li class="search-item border-bottom" v-show="flag" >没有找到匹配数据</li>
      </ul>
    </div>
  </div>
</div>

</template>

<script>
import Bscroll from 'better-scroll'
import {mapMutations} from 'vuex'
export default {
  name:"CitySearch",
  props:{
    cities:Object
  },
  mounted(){
    if(this.$refs.search){
      this.scroll = new Bscroll(this.$refs.search)
    }
  },
  data(){
    return{
      keyword:"",
      list:[],
      timer:null,
      flag:false
    }
  },
  computed:{
    showcity(){
      if(!this.keyword){
        return false
      }
      if(this.list.length){
        this.flag=false;
        console.log(this.flag)
        return true;
      }else{
        this.flag=true;
        return true;
      }
    }
  },
  methods:{
    handleClickName(city){
      this.changeCity(city)
      this.$router.push('/')
    },
    ...mapMutations(['changeCity'])
  },
  watch:{
    keyword (){
      if(this.timer){
        clearTimeout(this.timer)
      }
      this.timer = setTimeout(()=>{
        const result = [];
        for(let i in this.cities){
          this.cities[i].forEach((value) => {
            if(value.spell.indexOf(this.keyword)>-1 || 
            value.name.indexOf(this.keyword)>-1){
              result.push(value)
            }
          });
        }
        this.list=result
      },100)
    }
  }
}
</script>

<style lang="scss" scoped >
  @import '~styles/minin';
  .search{
    height: .6rem;
    background: $bc;
    padding: 0.1rem .2rem;
    .searchinput{
      height: .6rem;
      width: 100%;
      line-height: .6;
      border: 1px solid #ccc;
      text-align: center;
      @include borderRadius(.1rem);
    }
  }
  .search-content{
    z-index: 1;
    overflow: hidden;
    position: absolute;
    top: 1.68rem;
    left: 0;
    right: 0;
    bottom: 0;
    background: #eee;
    .search-item{
      line-height: .62rem;
      padding-left:.2rem ;
      color: #666;
    }
    .border-bottom{
      border-bottom: 1px solid #fff;
    }
  }
</style>